<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      title="部门列表"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'departName' }"
      :selectedKeys="selectedKeys"
      @select="handleSelect"
      @defSelect="defSelectData"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { queryMyDeptTreeList } from '/@/api/system/dept/dept.api';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select', 'defSelect'],
    setup(_, { emit }) {
      const treeData = ref([]);
      const selectedKeys = ref([]);
      async function fetch() {
        const myDeptList = await queryMyDeptTreeList();
        if (myDeptList && myDeptList.length > 0) {
          treeData.value = myDeptList as unknown as TreeItem[];
          //默认选择第一个
          selectedKeys.value = [myDeptList[0].key];
          defSelectData();
        }
      }
      function defSelectData() {
        emit('defSelect', selectedKeys);
      }
      function handleSelect(keys) {
        emit('select', keys[0]);
      }

      onMounted(() => {
        fetch();
      });
      return { treeData, handleSelect, selectedKeys, defSelectData };
    },
  });
</script>
